
#include <BBuffer>
#include "member_BBuffer.h"

using namespace BWE;

#define member					(*(member_BBuffer*)_ptr)
#define member_allocate()		_ptr = new member_BBuffer
#define member_release()		delete (member_BBuffer*)_ptr

BBuffer::BBuffer(int size)
{
	member_allocate();
	member.bytes.resize(size);
}
BBuffer::BBuffer(const BBuffer& other)
{
	member_allocate();
	member.bytes = buffer_member(&other)->bytes;
}
BBuffer::BBuffer(const BByteArray& bytes)
{
	member_allocate();
	*this = bytes;
}
BBuffer::~BBuffer()
{
	member_release();
}

void BBuffer::setData(const BByteArray& data)
{
	member.bytes = data;
}
void BBuffer::setData(const BByte* data, int size)
{
	member.bytes.clear();
	member.bytes.append(data, size);
}
const BByte* BBuffer::data() const
{
	return member.bytes.data();
}

bool BBuffer::seek(int offset) const
{
	if (!member.bytes.check(offset))
		return false;
	member.offset = offset;
	return true;
}
bool BBuffer::wseek(int offset)
{
	if (offset < 0)
		return false;
	if (offset > member.bytes.size())
		member.bytes.append((BByte)0, offset - member.bytes.size());
	member.offset = offset;
	return true;
}

bool BBuffer::resize(int size)
{
	member.bytes.resize(size);
	return true;
}
void BBuffer::reset(char value)
{
	member.bytes.fill(value);
}

bool BBuffer::isBegin() const
{
	return member.offset == 0;
}
bool BBuffer::isEnd() const
{
	return member.offset == member.bytes.size();
}

int BBuffer::offset() const
{
	return member.offset;
}
int BBuffer::size() const
{
	return member.bytes.size();
}

bool BBuffer::read(void* buffer, int size) const
{
	if (member.offset + size > member.bytes.size())
		return false;
	memcpy(buffer, member.bytes.data() + member.offset, size);
	member.offset += size;
	return true;
}
bool BBuffer::write(const void* buffer, int size)
{
	if(!member.bytes.append((BByte*)buffer, size))
		return false;
	member.offset += size;
	return true;
}

void BBuffer::operator = (const BByteArray& bytes)
{
	member.bytes = bytes;
}
void BBuffer::operator = (const BString& str)
{
	member.bytes.clear();
	member.bytes.append((const BByte*)str.cstr(), str.size() + 1);
}
void BBuffer::operator = (const char* cstr)
{
	if (cstr)
	{
		int size = (int)strlen(cstr) + 1;
		member.bytes.append((const BByte*)cstr, size);
	}
}
